// pages/home/home.js
var Zan = require('../../dist/index');
var bananer = require('../../template/HomeTemp.js');
var baseInfo = require('../../utils/base_info.js');
let network = null;
let utils = null;
let api = null;
// 获取应用实例
let app = getApp()
let count = 0;

/**
 * 所有商品 0 (旧数据) 
 * 商品详情 1 
 * 商品分类 2 
 * 优惠券列表 3 
 * 商品搜索 4 
 * 到店自提 5(旧数据) 
 * 拼团详情 6
 * 文章详情 7 
 * 文章分类 8 
 * 拼团列表 9
 * 积分商品列表 10 
 * 积分商品详情 11 
 * 分销页面 12 
 * 门店列表 13 
 * 门店详情 14
 */
Page(Object.assign({}, Zan.TopTips, {

  /**
   * 页面的初始数据
   */
  data: {
    bananer: {
      autoplay: true,
      interval: 5000,
      duration: 300,
      indicatorDots: true,
      circular: true
    },
    frame: [],
    popOn: null,
    coupon: [],
    showModalStatus: false,
    screenHeight: 0,
    isyouhuishow: false,
    showCenterBtn: true,
    showFillBtn: false,
    temp: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    network = new app.NetWorkUtils();
    utils = new app.Utils();
    api = new app.Api();
    this.setData({
      utils: utils,
      height: utils.windowSize().winWidth / 750 * 400,
      // videoWidth: utils.windowSize().winWidth / 750 * 670,
      videoHeight: utils.windowSize().winWidth / 750 * 402,
    });

    this.setData({
      bananer: {
        autoplay: true,
        interval: 5000,
        duration: 300,
        indicatorDots: true,
        circular: true,
        height: utils.windowSize().winWidth / 750 * 400
      }
    })


    /**
     * 如果有userId则直接获取首页数据，否则在回调jsCodeReadyCallback中获取
     */
    if (app.globalData.userId) {
      wx.setNavigationBarTitle({
        title: app.globalData.userAndTenantInfo.tenant.name,
      })
      bind(options);
      network._post_json(this, api.getHomeFarem, {}, success);
    } else {
      // 由于 openId 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userAndTenantInfoCallback = res => {
        wx.setNavigationBarTitle({
          title: res.tenant.name,
        })
        bind(options);
        network._post_json(this, api.getHomeFarem, {}, success);
      }
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // this.videoContext = wx.createVideoContext('myVideo')
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    app.globalData.timeStamp = app.globalData.timeStamp + 500;
    for (let i = 0; i < this.data.frame.length; i++) {
      if (this.data.frame[i].type == 5) {
        for (let j = 0; j < this.data.frame[i].sub.length; j++) {
          this['videoContext' + this.data.frame[i].sub[j].id].pause();
        }
      }
    }

    this.setData({
      showModalStatus: false
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
     wx.stopPullDownRefresh();
    this.setData({
      // videoHeight: utils.windowSize().winWidth / 750 * 402,
      frame: []
    })
    /**
     * 如果有userId则直接获取首页数据，否则在回调jsCodeReadyCallback中获取
     */
    if (app.globalData.userId) {
      network._post_json(this, api.getHomeFarem, {}, success);
    } else {
      // 由于 openId 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userAndTenantInfoCallback = res => {
        network._post_json(this, api.getHomeFarem, {}, success);
      }
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    
  },

  onBananerItemClick: function (e) {
    bananer.onBananerItemClick(this, e);
  },

  onNavigateItemClick: function (e) {
    bananer.onNavigateItemClick(this, e);
  },

  onRecommendItemClick: function (e) {
    bananer.onRecommendItemClick(this, e);
  },

  onSpellProductItemClick: function (e) {
    bananer.onSpellProductItemClick(this, e);
  },

  onArticleItemClick: function (e) {
    bananer.onArticleItemClick(this, e);
  },

  onImageHItemClick: function (e) {
    bananer.onImageHItemClick(this, e);
  },

  onVideoItemClick: function (e) {
    bananer.onVideoItemClick(this, e);
  },

  powerDrawer: function (e) {
    bananer.powerDrawer(this, e);
  },

  onAdvertItemClick: function (e) {
    bananer.onAdvertItemClick(this, e);
  },
  // 领取优惠券
  receiveCoupon: function (e) {
    this.setData({
      showModalStatus: false
    })
    bananer.receiveCoupon(this, e)
  },
  //点击领取优惠券
  clickhongbao: function (e) {

    bananer.clickhongbao(this, e)
  },
  //进入购物车
  go_shopcar: function (e) {
    wx.navigateTo({
      url: '/pages/shoppingCar/ShoppingCar',
    })
  },

  startPlay: function (e) {
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        if (res.system.indexOf("iOS") >= 0) {
          let id = e.target.dataset.id;
          for (var i = 0; i < that.data.frame.length; i++) {
            if (that.data.frame[i].type == 5) {
              for (let j = 0; j < that.data.frame[i].sub.length; j++) {
                if (id == that.data.frame[i].sub[j].id) {
                  wx.createVideoContext(id).play();
                } else {
                  wx.createVideoContext(that.data.frame[i].sub[j].id).pause();
                }
              }
            }
          }
        }
      }
    })
  },

  not: function (e) {
    let id = e.target.dataset.id;
    for (var i = 0; i < this.data.frame.length; i++) {
      if (this.data.frame[i].type == 5) {
        for (let j = 0; j < this.data.frame[i].sub.length; j++) {
          if (id == this.data.frame[i].sub[j].id) {
            wx.createVideoContext(id).play();
          } else {
            wx.createVideoContext(this.data.frame[i].sub[j].id).pause();
          }
        }
      }
    }
  },
}))


// 返回openId请求结果
var openIdSuccess = function (that, res) {
  console.log(res)
  // 得到openId
  app.globalData.openId = res.data.data.openid
  app.globalData.sessionKey = res.data.data.session_key

  network._post_json(that, api.getUserInfo, { appId: app.globalData.appId, openId: app.globalData.openId }, userAndTenantInfoSuccess);
}

// 返回openId请求失败结果
var fail = function (that, res) {
  console.log("服务器连接失败")
  console.log(res)
  network._error(api.wxError, res);
  count++;
  if (count < 3) {
    network._post1(that, api.wxUrl, { appId: app.globalData.appId, jsCode: app.globalData.jsCode }, openIdSuccess, fail);
  }
}


// 获取个人及商家信息结果
var userAndTenantInfoSuccess = function (that, res) {
  if (res.data.data) {
    var userAndTenantInfo = res.data.data;
    app.globalData.userAndTenantInfo = userAndTenantInfo;
    app.globalData.userId = userAndTenantInfo.id;
    app.globalData.tenantId = userAndTenantInfo.tenantId;

    if (app.userAndTenantInfoCallback) {
      app.userAndTenantInfoCallback(userAndTenantInfo)
    }

    wx.setNavigationBarTitle({
      title: res.data.data.tenant.name,
    })

    // 获取首页信息
    network._post_json(that, api.getHomeFarem, {}, success);

    // 获取用户信息
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: function (res) {
              // 可以将 res 发送给后台解码出 unionId
              console.log(res)
              app.globalData.userInfo = res.userInfo
              network._post_json(that, api.modifyUserInfo, { nickName: res.userInfo.nickName, avatarUrl: res.userInfo.avatarUrl, gender: app.globalData.userInfo.gender }, modifySuccess);
              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (app.userInfoReadyCallback) {
                app.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })

  }
}

// 首页控件请求返回结果
var success = function (that, res) {
  // 首页控件请求
  if (res.data.data) {
    for (var i = 0; i < res.data.data.applet.length; i++) {
      if (res.data.data.applet[i].backgroud) {
        res.data.data.applet[i].backgroud = colorRGB2Hex(res.data.data.applet[i].backgroud);
      } else {
        res.data.data.applet[i].backgroud = '#ffffff';
      }

      if (res.data.data.applet[i].type == 5) {
        let video = [];
        for (let j = 0; j < res.data.data.applet[i].sub.length; j++) {
          that['videoContext' + res.data.data.applet[i].sub[j].id] = wx.createVideoContext(res.data.data.applet[i].sub[j].id, that);
        }
      }

      if (res.data.data.applet[i].type == 7) {
        for (let j = 0; j < res.data.data.applet[i].sub.length; j++) {
          res.data.data.applet[i].sub[j].createDate = utils.formatDate06(new Date(res.data.data.applet[i].sub[j].createDate))
        }
      }
    }
    that.setData({
      frame: that.data.frame.concat(res.data.data.applet),
      popOn: res.data.data.popOn
    })
    if (res.data.data.popOn) {
      if (res.data.data.popOn.status == 1) {
        if (res.data.data.popOn.type == '广告') {
          that.setData({
            showModalStatus: true
          })
        } else {
          if (res.data.data.popOn.linkId) {
            var couponId = res.data.data.popOn.linkId.split(",")
            network._post_json(that, api.getCoupon, { couponId: couponId }, couponSuccess);
          }
        }
      }
    }
  }
}

var couponSuccess = function (that, res) {
  if (res.data.data) {
    var coupon = res.data.data;
    for (var i = 0; i < coupon.length; i++) {
      coupon[i].startTime = utils.formatDate02(new Date(coupon[i].startTime))
      coupon[i].endTime = utils.formatDate02(new Date(coupon[i].endTime))
    }
    that.setData({
      coupon: coupon,
      showModalStatus: true
    })
  }
}

var bind = function (options) {
  if (options.scene) {
    var scene = decodeURIComponent(options.scene);
    if (scene.substring(0, 1) == 'u') {
      wx.request({
        url: api.bindUserFormQRcode,
        data: {
          openId: app.globalData.openId,
          userId: app.globalData.userId,
          tenantId: app.globalData.tenantId,
          distributorId: scene.substring(2, scene.length),
        },
        method: 'POST',
        success: function (res) {
        }
      });
    } else {
      app.globalData.storeId == scene.substring(2, scene.length);
    }
  }
  if (options.shared) {
    wx.request({
      url: api.bindUserFormQRcode,
      data: {
        openId: app.globalData.openId,
        userId: app.globalData.userId,
        tenantId: app.globalData.tenantId,
        distributorId: options.shared,
      },
      method: 'POST',
      success: function (res) {
      }
    });
  }
}

var colorRGB2Hex = function (color) {
  var rgb = color.split(',');
  var r = parseInt(rgb[0].split('(')[1]);
  var g = parseInt(rgb[1]);
  var b = parseInt(rgb[2].split(')')[0]);

  var hex = "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
  return hex;
}
